package com.xc.disk.web.controller;

import com.xc.disk.config.Constants;
import com.xc.disk.entity.UserEntity;
import com.xc.disk.exception.OperateException;
import com.xc.disk.service.UserService;
import com.xc.disk.utils.RedisUtils;
import com.xc.tool.utils.IpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>项目名称: Stars</p>
 * <p>描述: 分享页面</p>
 * <P>创建人: 小程</p>
 * <P>创建人邮箱: 779943476@qq.com</p>
 * <p>创建时间: 2019/7/2</p>
 *
 * @version v1.0
 */
@Controller
public class SharePageController {


    @Autowired
    private Constants constants;
    @Autowired
    private UserService userService;


    @GetMapping("/share/page/{shareCode}")
    public void getSharePage(@PathVariable String shareCode,
                             HttpServletRequest request,
                             HttpServletResponse response) {

        try {
            String ip = IpUtils.getClientIp(request);
            String data = RedisUtils.get(shareCode + "_" + ip);
            if (data == null) {
                UserEntity userEntity = userService.getUserByShareCode(shareCode);
                userService.computeFreeFlow(userEntity.getId(), 1048576, true);
                RedisUtils.set(shareCode + "_" + ip, userEntity.getId(), 1800000l);
            }
            response.sendRedirect(constants.getSharePageUrl());
        } catch (IOException e) {
            throw new OperateException("f015", "重定向下载失败！");
        }
    }

}
